﻿using System;

using System.Net.DnsToolkit.Packet;
using System.Net.DnsToolkit.Serializer.Stream.Extension;

namespace System.Net.DnsToolkit.Serializer.Stream.Writer {
    public class HeaderWriter : IHeaderWriter<System.IO.Stream> {
        
        public void Write(System.IO.Stream destination, IHeader header) {

            destination.Write16((ushort)header.Id);

            var bqoatr = (byte)(
                (byte)header.QueryType << 7
                | (byte)header.OpCode << 3
                | (header.AuthoritativeAnswer ? 1 : 0) << 2
                | (header.Truncation ? 1 : 0) << 1
                | (header.RecursionDesired ? 1 : 0) << 0);

            destination.Write8(bqoatr);

            var brranr = (byte)(
                (header.RecursionAvailable ? 1 : 0) << 7
                | (header.Reserved ? 1 : 0) << 6
                | (header.AnswerAuthenticated ? 1 : 0) << 5
                | (header.NotAuthenticatedAcceptable ? 1 : 0) << 6
                | (byte)header.ResponseCode << 0);

            destination.Write8(brranr);

            destination.Write16(header.QuestionCount);
            destination.Write16(header.AnswerCount);
            destination.Write16(header.ResourceCount);
            destination.Write16(header.AuthorityCount);

        }

    }
}
